package com.zmn.plat.admin.controller.orderconfig.track;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.DictModel;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.common.dto.dept.DeptDRO;
import com.zmn.mcc.dubbo.dto.DubboConsts;
import com.zmn.mcc.dubbo.interfaces.dept.DeptListRemoteService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.plat.common.constant.BaseAreaConsts;
import com.zmn.plat.model.entity.orderconfig.track.OrderTrackQuery;
import com.zmn.plat.model.entity.orderconfig.track.category.OrderTrackCategory;
import com.zmn.plat.model.entity.orderconfig.track.category.OrderTrackCategoryQuery;
import com.zmn.plat.model.vo.orderconfig.track.OrderTrackVO;
import com.zmn.plat.services.interfaces.orderconfig.track.category.OrderTrackCategoryService;
import com.zmn.ums.common.chs.dro.config.category.ChsCategoryDRO;
import com.zmn.ums.common.chs.dro.content.ChsContentDRO;
import com.zmn.ums.common.chs.query.config.category.ChsCategoryQuery;
import com.zmn.ums.common.chs.query.config.content.ChsContentQuery;
import com.zmn.ums.dubbo.dto.abnor.AbnormalCategoryDIO;
import com.zmn.ums.dubbo.dto.abnor.AbnormalCategoryDRO;
import com.zmn.ums.dubbo.dto.abnor.AbnormalContentDIO;
import com.zmn.ums.dubbo.dto.abnor.AbnormalContentDRO;
import com.zmn.ums.dubbo.interfaces.abnor.AbnormalCategoryRemoteService;
import com.zmn.ums.dubbo.interfaces.abnor.AbnormalContentListRemoteService;
import com.zmn.ums.dubbo.interfaces.chs.config.category.ChsCategoryListRemoteService;
import com.zmn.ums.dubbo.interfaces.chs.config.content.ChsContentListRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tanbiao
 * @description ：跟单分类
 * @modifier
 * @since 2020/11/17 16:49
 **/
@Controller
@RequestMapping("/orderconfig/track/")
@Slf4j
public class OrderTrackListController extends OrderTrackBaseController {
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private DeptListRemoteService deptListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ChsCategoryListRemoteService categoryListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ChsContentListRemoteService contentListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private AbnormalCategoryRemoteService abnormalCategoryRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private AbnormalContentListRemoteService abnormalContentListRemoteService;
    @Resource
    private OrderTrackCategoryService orderTrackCategoryService;

    /**
     * 描述: 跟单分类列表
     *
     * @param query 查询实体
     * @return ModelAndView
     * @author tanbiao
     * @since 2020/11/17
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "list")
    @RequiresPermissions("/orderconfig/track/list.action")
    public ModelAndView list(@ModelAttribute OrderTrackQuery query) {
        ModelAndView mav = new ModelAndView("orderconfig/track/list");
        List<OrderTrackVO> items = orderTrackService.listPageByQuery(query);
        transLateOrderStatus(items);
        ResponseDTO<List<DeptDRO>> deptRes = deptListRemoteService.listDeptByLevelAndStatus(GlobalConsts.LEVEL_2, GlobalConsts.YES);
        if (deptRes.isSuccess()) {
            mav.addObject("deptList", deptRes.getData());
        }
        OrderTrackCategoryQuery trackCategoryQuery = new OrderTrackCategoryQuery();
        List<OrderTrackCategory> categList = orderTrackCategoryService.listByQuery(trackCategoryQuery);

        mav.addObject("items", items);
        mav.addObject("vo", query);
        mav.addObject("bizTypeList", com.zmn.plat.common.dictionary.ProductDict.listBizType());
        mav.addObject("levelList", com.zmn.plat.common.dictionary.OrderTrackDict.listOrderTrackLevel());
        mav.addObject("trackOperatorList", com.zmn.plat.common.dictionary.OrderTrackDict.listOrderTrackOperator());
        mav.addObject("legacyList", GlobalDict.getYesOrNoList());
        mav.addObject("categList", categList);
        mav.addObject("trackOrderStatus", OrderStatusConsts.getWorkStatusList().stream().map(e -> new VtDTO(e.getKey(), e.getValue())).collect(Collectors.toList()));
        return mav;
    }

    /**
     * 功能描述 ：详情页面
     *
     * @param trackId
     * @return org.springframework.web.servlet.ModelAndView
     * @author tanbiao
     * @modifier
     * @since 2020/11/17
     */
    @RequestMapping(value = "detail")
    @RequiresPermissions("/orderconfig/track/detail.action")
    public ModelAndView detail(@RequestParam(value = "trackId", defaultValue = "0") Integer trackId) {
        ModelAndView mav = new ModelAndView("orderconfig/track/detail");
        OrderTrackVO vo = null;
        if (trackId == null || trackId == 0) {
            vo = new OrderTrackVO();
        } else {
            vo = Optional.ofNullable(orderTrackBService.getById(trackId)).orElse(new OrderTrackVO());
        }
        if (vo.getSort() == null) {
            Integer sort = orderTrackService.findMaxSort();
            sort = sort == null ? 1 : sort + 1;
            vo.setSort(sort);
        }
        Integer categId = vo.getCategId();

        // 跟单类型
        OrderTrackCategoryQuery trackCategoryQuery = new OrderTrackCategoryQuery();
        List<OrderTrackCategory> categList = orderTrackCategoryService.listByQuery(trackCategoryQuery);

        // 新增只出现可以用的分类
        if (trackId == null || trackId == 0) {
            categList = categList.stream().filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES)).collect(Collectors.toList());
        } else {
            // 修改,保证当前的分类包含其中，其余可修改的为启用状态
            categList = categList.stream().filter(e -> (Objects.equals(e.getStatus(), GlobalConsts.YES) || Objects.equals(e.getCategId(), categId))).collect(Collectors.toList());
        }
        // 投诉一级分类
        List<VtDTO> complainOneList = listComplainByLevel(BaseAreaConsts.AREA_LEVEL_ONE, null, vo.getComplainOneId());
        // 投诉二级分类
        List<VtDTO> complainTwoList = new ArrayList<>();
        if (NumberUtil.isPositiveInteger(vo.getComplainOneId())) {
            complainTwoList = listComplainByLevel(null, vo.getComplainOneId(), vo.getComplainTwoId());
        }
        // 投诉内容
        List<VtDTO> complainContentList = new ArrayList<>();
        if (NumberUtil.isPositiveInteger(vo.getComplainTwoId())) {
            complainContentList = listComplainContentByLevel(vo.getComplainOneId(), vo.getComplainTwoId(), vo.getComplainContentId());
        }
        // 异常一级分类
        List<VtDTO> abnorOneList = listAbnorByLevel(BaseAreaConsts.AREA_LEVEL_ONE, null, vo.getAbnorOneId());
        // 异常二级分类
        List<VtDTO> abnorTwoList = new ArrayList<>();
        if (NumberUtil.isPositiveInteger(vo.getAbnorOneId())) {
            abnorTwoList = listAbnorByLevel(null, vo.getAbnorOneId(), vo.getAbnorTwoId());
        }
        // 异常内容
        List<VtDTO> abnorContentList = new ArrayList<>();
        if (NumberUtil.isPositiveInteger(vo.getAbnorTwoId())) {
            abnorContentList = listAbnorContentByLevel(vo.getAbnorOneId(), vo.getAbnorTwoId(), vo.getAbnorContentId());
        }
        mav.addObject("complainOneList", complainOneList);
        mav.addObject("abnorOneList", abnorOneList);
        mav.addObject("complainTwoList", complainTwoList);
        mav.addObject("complainContentList", complainContentList);
        mav.addObject("abnorTwoList", abnorTwoList);
        mav.addObject("abnorContentList", abnorContentList);
        mav.addObject("bizTypeList", com.zmn.plat.common.dictionary.ProductDict.listBizType());
        mav.addObject("levelList", com.zmn.plat.common.dictionary.OrderTrackDict.listOrderTrackLevel());
        mav.addObject("trackOperatorList", com.zmn.plat.common.dictionary.OrderTrackDict.listOrderTrackOperator());
        mav.addObject("legacyList", GlobalDict.getYesOrNoList());
        mav.addObject("categList", categList);


        mav.addObject("vo", vo);
        return mav;
    }

    @RequestMapping(value = "listAbnor")
    @ResponseBody
    public ResponseDTO<List<VtDTO>> listAbnor(HttpServletResponse response, @RequestParam(value = "oneLevelId", defaultValue = "0") Integer oneLevelId,
                                              @RequestParam(value = "twoLevelId", defaultValue = "0") Integer twoLevelId) {
        // 一级必传
        if (!NumberUtil.isPositiveInteger(oneLevelId)) {
            return ResponseDTO.success();
        }
        // 二级为空，根据一级查询二级
        if (!NumberUtil.isPositiveInteger(twoLevelId)) {
            List<VtDTO> abnors = listAbnorByLevel(null, oneLevelId, null);
            return ResponseDTO.success(abnors);
        }

        // 存在二级id，查询的是内容
        List<VtDTO> abnors = listAbnorContentByLevel(oneLevelId, twoLevelId, null);
        return ResponseDTO.success(abnors);
    }

    @RequestMapping(value = "lisComplain")
    @ResponseBody
    public ResponseDTO<List<VtDTO>> lisComplain(HttpServletResponse response, @RequestParam(value = "oneLevelId", defaultValue = "0") Integer oneLevelId,
                                                @RequestParam(value = "twoLevelId", defaultValue = "0") Integer twoLevelId) {
        // 一级必传
        if (!NumberUtil.isPositiveInteger(oneLevelId)) {
            return ResponseDTO.success();
        }
        // 二级为空，根据一级查询二级
        if (!NumberUtil.isPositiveInteger(twoLevelId)) {
            List<VtDTO> complains = listComplainByLevel(null, oneLevelId, null);
            return ResponseDTO.success(complains);
        }

        // 存在二级id，查询的是内容
        List<VtDTO> complains = listComplainContentByLevel(oneLevelId, twoLevelId, null);
        return ResponseDTO.success(complains);
    }


    @RequestMapping(value = "listDept")
    @ResponseBody
    public ResponseDTO<List<VtDTO>> listDept() {
        List<VtDTO> depts = new ArrayList<>();
        ResponseDTO<List<DeptDRO>> deptRes = deptListRemoteService.listDeptByLevelAndStatus(GlobalConsts.LEVEL_2, GlobalConsts.YES);
        if (deptRes.isSuccess()) {
            depts = deptRes.getData().stream().map(e -> new VtDTO(e.getDeptId(), e.getDeptName())).collect(Collectors.toList());
        }
        return ResponseDTO.success(depts);
    }

    @RequestMapping(value = "listOrderStatus")
    @ResponseBody
    public ResponseDTO<List<VtDTO>> listOrderStatus() {
        List<DictModel> orderStatusList = OrderStatusConsts.getWorkStatusList();
        return ResponseDTO.success(orderStatusList.stream().map(e -> new VtDTO(e.getKey(), e.getValue())).collect(Collectors.toList()));
    }

    private void transLateOrderStatus(List<OrderTrackVO> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(vo -> {
                String orderStatus = vo.getOrderStatus();
                if (StringUtil.isNotBlank(orderStatus)) {
                    List<Integer> statusList = StringUtil.convertStrsToList(orderStatus);
                    vo.setOrderStatus(statusList.stream().map(e -> OrderStatusConsts.getWorkStatusName(e)).collect(Collectors.joining("、")));
                }
                String operator = vo.getTrackOperator();
                if (StringUtil.isNotBlank(operator)) {
                    vo.setTrackOperatorSystem(operator.indexOf(GlobalConsts.OPERATE_USER_TYPE_SYSTEM + "") != -1 ? "是" : "否");
                    List<Integer> statusList = StringUtil.convertStrsToList(operator);
                    vo.setTrackOperator(statusList.stream().map(e -> GlobalConsts.getOperatorTypeName(e)).collect(Collectors.joining("、")));
                }
                String billType = vo.getBillType();
                if (StringUtil.isNotBlank(billType)) {
                    List<Integer> statusList = StringUtil.convertStrsToList(billType);
                    vo.setBillType(statusList.stream().map(e -> OrderConsts.getOrderTypeName(e)).collect(Collectors.joining("、")));
                }
            });
        }
    }

    private List<VtDTO> listComplainByLevel(Integer level, Integer parentId, Integer currentId) {
        ChsCategoryQuery categoryDIO = new ChsCategoryQuery();
        if (NumberUtil.isPositiveInteger(level)) {
            categoryDIO.setLevel(level);
        }
        if (NumberUtil.isPositiveInteger(parentId)) {
            categoryDIO.setParentId(parentId);
        }
        ResponseDTO<List<ChsCategoryDRO>> responseDTO = categoryListRemoteService.listByQuery(categoryDIO);
        if (responseDTO.isSuccess()) {
            List<VtDTO> retList = responseDTO.getData().stream().filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES) || Objects.equals(currentId, e.getCategId()))
                    .map(e -> new VtDTO(e.getCategId(), e.getName())).collect(Collectors.toList());
            return retList;
        }
        return Collections.emptyList();
    }

    private List<VtDTO> listComplainContentByLevel(Integer oneId, Integer twoId, Integer currentId) {
        ChsContentQuery categoryDIO = new ChsContentQuery();
        categoryDIO.setCategOneId(oneId);
        categoryDIO.setCategTwoId(twoId);
        ResponseDTO<List<ChsContentDRO>> responseDTO = contentListRemoteService.listByQuery(categoryDIO);
        if (responseDTO.isSuccess()) {
            List<VtDTO> retList = responseDTO.getData().stream().filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES) || Objects.equals(currentId, e.getContentId()))
                    .map(e -> new VtDTO(e.getContentId(), e.getContent())).collect(Collectors.toList());
            return retList;
        }
        return Collections.emptyList();
    }


    private List<VtDTO> listAbnorByLevel(Integer level, Integer parentId, Integer currentId) {
        AbnormalCategoryDIO categoryDIO = new AbnormalCategoryDIO();
        if (NumberUtil.isPositiveInteger(level)) {
            categoryDIO.setLevel(level);
        }
        if (NumberUtil.isPositiveInteger(parentId)) {
            categoryDIO.setParentId(parentId);
        }
        ResponseDTO<List<AbnormalCategoryDRO>> responseDTO = abnormalCategoryRemoteService.listByQuery(categoryDIO);
        if (responseDTO.isSuccess()) {
            List<VtDTO> retList = responseDTO.getData().stream().filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES) || Objects.equals(currentId, e.getCategId()))
                    .map(e -> new VtDTO(e.getCategId(), e.getName())).collect(Collectors.toList());
            return retList;
        }
        return Collections.emptyList();
    }

    private List<VtDTO> listAbnorContentByLevel(Integer oneId, Integer twoId, Integer currentId) {
        AbnormalContentDIO categoryDIO = new AbnormalContentDIO();
        categoryDIO.setCategOneId(oneId);
        categoryDIO.setCategTwoId(twoId);
        ResponseDTO<List<AbnormalContentDRO>> responseDTO = abnormalContentListRemoteService.listByQuery(categoryDIO);
        if (responseDTO.isSuccess()) {
            List<VtDTO> retList = responseDTO.getData().stream().filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES) || Objects.equals(currentId, e.getId()))
                    .map(e -> new VtDTO(e.getId(), e.getContent())).collect(Collectors.toList());
            return retList;
        }
        return Collections.emptyList();
    }

}
